<template>
  <!-- 单独的员工列表组件 -->
  <div id="employeelist">
    <vxe-toolbar perfect>
      <template #buttons>
        <div class="smallToolTitle">员工信息</div>
        <vxe-input style="width: 130px" v-model="searchForm.searchValue" clearable class="vxeInputSearch" type="search" placeholder="关键字查询" @clear="findPloyeeList" @keyup="keyupEnter" @search-click="handleSearch(searchForm.searchValue)"></vxe-input>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findPloyeeList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addPloyee"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="数据同步" :loading="showDataLoading" @click="pullPloyee"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="生成用户" :loading="userLoading" @click="batchCreateUser"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="生成护士用户" :loading="userLoading" @click="batchCreateHSUser"></vxe-button>

      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table ref="ployeeTable" :loading="showLoading" height="auto" class="mytable-scrollbar" border="inner" :data="ployeeList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
          isArrow: true,
          isTab: true,
          isEdit: true
        }" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30"></vxe-column>
        <vxe-column type="seq" title="序号" width="40" align="center"></vxe-column>
        <vxe-column field="code" title="编码" width="120">
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="editPloyee(row)">
              {{
              row.code
              }}
            </el-link>
          </template>
        </vxe-column>
        <vxe-column field="name" title="名称" width="100"></vxe-column>
        <vxe-column field="position" title="岗位" width="100">
          <template #default="{ row }">
            <span>{{ row.position ? row.position.name : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="post" title="职务" width="100">
          <template #default="{ row }">
            <span>{{ row.post ? row.post.name : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="professionalTitle" title="职称" min-width="100">
          <template #default="{ row }">
            <span>{{ row.professionalTitle ? row.professionalTitle.name : '' }}</span>
          </template>
        </vxe-column>

        <vxe-column title="操作" width="90" align="center" fixed="right">
          <template #default="{ row }">
            <vxe-button  type="text" status="primary" icon="vxe-icon-edit" circle @click.native="editPloyee(row)"></vxe-button>
            <vxe-button  type="text" status="danger" icon="vxe-icon-delete" circle @click.native="deletePloyee(row.id)"></vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <!-- <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ]" @page-change="handleSizeChange"></vxe-pager> -->
    <vxe-modal title="设置信息" v-model="showPloyeeDialog" width="750px" :position="{ top: 150 }" show-zoom resize remember destroy-on-close :lock-view="false" :mask="false" :transfer="true">
      <template #default>
        <!-- @tab-click="clickTabs" -->
        <el-tabs v-model="activeNameCard">
          <el-tab-pane label="基本信息" name="first">
            <div class="baseInfo" style="height: 300px">
              <EditEmployees ref="refEditEmployees" @closePerDialog="closePerDialog" @findPloyeeList="findPloyeeList" />
            </div>
          </el-tab-pane>

          <!-- <el-tab-pane
              label="修改授权码"
              name="secord"
              :disabled="!(ployeeForm.id && ployeeForm.id.length > 0)"
              class="modifyCode"
            >
              <div class="" style="height: 300px">
                <SetEmployPuthorization
                  ref="refSetEmployPuthorization"
                  @closePerDialog="closePerDialog"
                />
              </div>
            </el-tab-pane>-->

          <el-tab-pane label="授权部门" name="third" :disabled="!(ployeeForm.id && ployeeForm.id.length > 0)" class="authDepartment">
            <div style="height: 300px">
              <EmpAuthDeparts ref="refEmpAuthDeparts" @closePerDialog="closePerDialog" />
            </div>
          </el-tab-pane>

          <el-tab-pane label="电子签名" name="forth" :disabled="!(ployeeForm.id && ployeeForm.id.length > 0)" class="elesignature">
            <div style="height: 300px">
              <Signature ref="refSignature" @closePerDialog="closePerDialog" />
            </div>
          </el-tab-pane>

          <el-tab-pane label="员工添加关联用户" name="fifth" :disabled="!(ployeeForm.id && ployeeForm.id.length > 0)" class="contactUser">
            <div style="height: 300px">
              <EmpRelationUser ref="refEmpRelationUser" @closePerDialog="closePerDialog" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
    </vxe-modal>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, nextTick, handleError, onMounted } from 'vue';
import { AppStore } from '../../stores/store';
let { proxy }: any = getCurrentInstance();
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息

import EditEmployees from '@/views/system_set/EditEmployees.vue'; //基本信息
import SetEmployPuthorization from '@/views/system_set/SetEmployPuthorization.vue'; //修改授权码
import EmpAuthDeparts from '@/views/system_set/EmpAuthDeparts.vue'; //授权部门
import Signature from '@/views/system_set/Signature.vue'; //电子签名
import EmpRelationUser from '@/views/system_set/EmpRelationUser.vue'; //员工添加关联用户
import { LocPost } from '@/utils/LocRequestHelper';

// 全局变量定义区 ==========
let store = AppStore();

// 获取模块id
const moduleId = localStorage.getItem('moduleId');
// 功能点权限
let modulePoitPre = reactive([]);
// 通过权限获取功能点
let modulePointMap = store.userInfo.modulePointMap;

// 获取屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);

//暴露属性和方法
defineExpose({
  initPage
});
let refEditEmployees: any = ref(null); //基本信息
let refSetEmployPuthorization: any = ref(null); //授权码
let refEmpAuthDeparts: any = ref(null); //授权部门
let refSignature: any = ref(null); //电子签名
let refEmpRelationUser: any = ref(null); //员工添加关联用户

// 要传给tab子组件的值
let searchForm = reactive({
  searchValue: '',
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName,
  deptId: '',
  deptName: ''
});

let ployeeForm = reactive({
  id: '',
  code: '',
  name: '',
  orgId: '',
  orgName: '',
  deptId: '',
  deptName: '',
  positionId: '',
  positionName: '',
  postId: '',
  postName: '',
  profesId: '',
  profesName: '',
  isDeactivated: true
});

let showLoading = ref(false); //刷新+获取表格加载状态
let showDataLoading = ref(false);
let userLoading = ref(false);

let ployeeTable = ref(); //员工表格ref
let ployeeList: any = reactive([]); //员工表格列表数据

const showPloyeeDialog = ref(false); //弹框展开状态
let activeNameCard = ref('secord');

// 条数/页
const PageSizeList = [50000, 50000, 100, 200, 500];

let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 方法定义区 =============
function initPage(row) {
  ployeeForm.orgId = row.orgId;
  ployeeForm.orgName = row.orgName;

  searchForm.orgId = row.orgId;
  searchForm.deptId = row.deptId;

  findPloyeeList(); //获取员工列表信息
}

function getModulePointMap() {
  if (Object.keys(modulePointMap).includes(moduleId)) {
    modulePoitPre.push(...modulePointMap[moduleId]);
  }
}

// 页码改变
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findPloyeeList();
}

// 页面加载时更新部门列表(右侧)
// onMounted(() => {
proxy.$nextTick(() => {
  findPloyeeList();
  getModulePointMap();
});

// });

// 获取员工列表
function findPloyeeList() {
  showLoading.value = true;
  ployeeList.length = 0;
  const $table = ployeeTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
  }
  const url = '/api/sys/hisEmployee/findAllHisEmployeeListByOrgDept';
  const params = {
    orgId: searchForm.orgId,
    deptId: searchForm.deptId,
    pageIndex: page.currentPage,
    pageSize: page.pageSize,
    searchValue: searchForm.searchValue
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      page.totalResult = res.data.total;
      ployeeList.length = 0;
      ployeeList.push(...res.data.records);
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      VxeMessage('获取员工列表失败', VxeNotifyType.error);
    });
}

// 搜索/查询
function handleSearch(searchValue: any) {
  const $table = ployeeTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
  }
  ployeeList.length = 0;
  const url = '/api/sys/hisEmployee/findAllHisEmployeeListByOrgDept';
  const params = {
    orgId: searchForm.orgId,
    deptId: searchForm.deptId,
    pageIndex: 1,
    pageSize: 50000,
    seachValue: searchValue
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      page.totalResult = res.data.total;
      ployeeList.length = 0;
      ployeeList.push(...res.data.records);
    })
    .catch((err: any) => {
      VxeMessage('搜索失败', VxeNotifyType.error);
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(searchForm.searchValue);
  }
}
// 同步数据
async function pullPloyee() {
  showDataLoading.value = true;
  const url = '/api/sys/hisEmployee/syncPubEmployees';
  const params = {
    url: (window as any).apiUrl.VUE_APP_INTERFACE_URL + '/lisInterface/lisInterfacePost',
    code: 'GET_EMPLOYEE'
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      showDataLoading.value = false;
      findPloyeeList();
    })
    .catch((err: any) => {
      showDataLoading.value = false;
      VxeMessage('同步失败', VxeNotifyType.error);
    });
}
function batchCreateUser() {
  const sltPloyees = (proxy.$refs.ployeeTable as any).getCheckboxRecords();
  if (!(sltPloyees.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    userLoading.value = true;
    const data = { pubEmployeeList: sltPloyees };
    const url = '/api/sys/hisEmployee/hisEmployeeBatchCreateUser';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (res.status.code === 1) {
          (proxy.$refs.ployeeTable as any).clearCheckboxRow();
          VxeMessage('成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        userLoading.value = false;
      })
      .catch((err: any) => {
        userLoading.value = false;
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function batchCreateHSUser() {
  const sltPloyees = (proxy.$refs.ployeeTable as any).getCheckboxRecords();
  if (!(sltPloyees.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    userLoading.value = true;
    const data = { pubEmployeeList: sltPloyees };
    const url = '/api/sys/hisEmployee/hisEmployeeBatchCreateHSUser';
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        if (res.status.code === 1) {
          (proxy.$refs.ployeeTable as any).clearCheckboxRow();
          VxeMessage('成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        userLoading.value = false;
      })
      .catch((err: any) => {
        userLoading.value = false;
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 判断弹框显示的标题
function titleType() {
  if (ployeeForm.id) {
    return `编辑`;
  } else if (!ployeeForm.id) {
    return `新建`;
  }
}

// 新建员工弹框
function addPloyee() {
  activeNameCard.value = 'first';
  titleType();

  ployeeForm.id = '';
  ployeeForm.code = '';
  ployeeForm.name = '';
  ployeeForm.orgId = '';
  ployeeForm.orgName = '';
  ployeeForm.deptId = '';
  ployeeForm.deptName = '';
  ployeeForm.positionId = '';
  ployeeForm.positionName = '';
  ployeeForm.postId = '';
  ployeeForm.postName = '';
  ployeeForm.profesId = '';
  ployeeForm.profesName = '';

  showPloyeeDialog.value = true;
  proxy.$nextTick(() => {
    refEditEmployees.value.init(searchForm); //基本信息组件
  });
}

// 点击编辑弹框
function editPloyee(item: any) {
  activeNameCard.value = 'first'; //卡片栏每次打开弹窗后默认在第一个基本信息上
  titleType(); //判断标题
  ployeeForm.id = item.id;
  ployeeForm.code = item.code;
  ployeeForm.name = item.name;
  ployeeForm.deptId = item.deptId;
  ployeeForm.deptName = item.deptName;
  ployeeForm.orgId = item.orgId;
  ployeeForm.orgName = item.orgName;

  showPloyeeDialog.value = true;
  proxy.$nextTick(() => {
    refEditEmployees.value.init(item); //基本信息组件
    //refSetEmployPuthorization.value.init(item); //授权码组件
    refEmpAuthDeparts.value.init(item); //授权部门组件
    refSignature.value.init(item); //授权电子签名组件
    refEmpRelationUser.value.init(item); //员工添加关联用户组件
  });
}

// 删除员工
function deletePloyee(id: any) {
  //   console.groupCollapsed(id);
  proxy
    .$confirm('确定删除此员工？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/api/sys/hisEmployee/deleteHisEmployeeById/' + id;
      proxy.$http
        .delete(url)
        .then((res: any) => {
          findPloyeeList();
          VxeMessage('删除员工成功', VxeNotifyType.success);
        })
        .catch((err: any) => {
          findPloyeeList();
          VxeMessage('删除员工失败', VxeNotifyType.error);
        });
    })
    .catch((err: any) => {
      // VxeMessage('删除部门调用接口失败', 'error');
    });
}

// 保存(未用到)
function opened() {
  const editEmployees: any = proxy.$refs.editEmployees;
  editEmployees.ployeeForm = ployeeForm;
}

// 父组件接收@关闭弹窗
function closePerDialog() {
  showPloyeeDialog.value = false;
}

// 取消关闭弹框
function closeDialog() {
  showPloyeeDialog.value = false;
}

// 弹框标签栏切换
function clickTabs(tab: any, event: any) {
  if (tab.name === 'third') {
    const empAuthDeparts: any = proxy.$refs.empAuthDeparts;
    empAuthDeparts.empAuthDepartForm.id = ployeeForm.id;
    empAuthDeparts.findAuthDepartsById();
  } else if (tab.name === 'second') {
    const setEmployPuthorization: any = proxy.$refs.setEmployPuthorization;
    setEmployPuthorization.authForm.id = ployeeForm.id;
  } else if (tab.name === 'first') {
    const editEmployees: any = proxy.$refs.editEmployees;
  }
}

// -----------------------------------

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
</script>

<style lang="scss" scoped>
#employeelist {
  height: 100%;
  // 附加按钮间距
  .button-blue {
    margin: 5px 0 5px 5px;
  }
  .tableBox {
    height: calc(100% - 39px);

    // :deep(.vxe-table--render-wrapper) {
    //   height: 100%;
    //   .vxe-table--main-wrapper {
    //     height: 100%;
    //     .vxe-table--body-wrapper {
    //       height: calc(100% - 26px) !important;
    //     }
    //   }
    // }
    // :deep(.vxe-table--render-default) {
    //   height: calc(100% - 36px) !important;
    // }
  }
}
</style>
